<template>
  <div style="border: 1px solid #ccc">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode"/>
    <Editor
        style="height: 400px; overflow-y: hidden;"
        :class="readonly ? 'wang_editor' : ''"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
        @customUpload="onCustomUpload"
        @onBlur="handleBlur"
        ref="wangeditorRef"
    />
  </div>
</template>

<script setup>
import {defineProps, defineEmits, ref, shallowRef, watch, onBeforeUnmount} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import doThis from "@/api/getData";

const props = defineProps({
  htmls: {
    type: String,
    default: ""
  },
  value: {
    type: String,
    default: ""
  },
  readonly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(["update:value", "blur"])

const editorRef = shallowRef()
const valueHtml = ref('')
const mode = ref('simple')
const toolbarConfig = {
  excludeKeys: ['insertVideo', 'insertTable', 'fullScreen', 'undo', 'redo', 'todo']
}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {}
}
editorConfig.MENU_CONF['uploadImage'] = {
  // base64LimitSize: 5 * 1024 * 1024
  // withCredentials: true,
  async customUpload(file, insertFn) {
    let data = new FormData()
    data.append('file',file)
    doThis.doPost("http://localhost:8081/upload", data).then(res => {
      insertFn(res.data.url)
    })
  }
}

const handleBlur = () => {
  emit('blur')
}

const onCustomUpload = () => {
  // 在此处定义自定义上传的逻辑
}

const handleCreated = (editor) => {
  editorRef.value = editor
  if (props.readonly) {
    editorRef.value.disable()
  }
}

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

watch(valueHtml, (n) => {
  emit('update', n)
})
</script>